<template>
  <div class="page-container">
    <div class="page-card-container">
      <a-form class="mb-20" :model="pageSet" layout="inline">
        <a-form-item label="角色名称">
          <a-input v-model:value="pageSet.name" allow-clear></a-input>
        </a-form-item>
        <a-form-item>
          <div class="flex-row-ycenter">
            <div class="commonBtn-primary mr-10" @click="loadPagination(true)">
              搜索
            </div>
            <div class="commonBtn-primary" @click="goHandle(1)">新增</div>
          </div>
        </a-form-item>
      </a-form>
      <a-table
        size="small"
        row-key="id"
        :loading="tableLoading"
        :dataSource="tableData"
        :columns="columns"
        bordered
        :pagination="false"
        @resizeColumn="handleResizeColumn"
      >
        <template #bodyCell="{text, record, index, column}">
          <div
            class="flex-row-xy-center c-primaryColor fs-12"
            v-if="column.dataIndex == 'handle'"
          >
            <span class="mr-10 pointer" @click="goHandle(2, record)">编辑</span>
            <span class="mr-10 pointer" @click="goHandle(4, record)"
              >菜单授权</span
            >
            <!-- <span class="mr-10 pointer" @click="goHandle(5, record)"
              >数据授权</span
            > -->
            <span class="pointer" @click="goHandle(3, record, index)"
              >删除</span
            >
          </div>
        </template>
      </a-table>
      <Pagination
        class="mt-10"
        :page-set="pageSet"
        :load-pagination="loadPagination"
      ></Pagination>
      <a-drawer
        width="50%"
        v-model:open="showModal"
        :title="handleTitle"
        @ok="showModalCon"
      >
        <a-form :model="form" ref="formRef" :label-col="{span: 8}">
          <template v-if="handleType === 1 || handleType === 2">
            <a-row>
              <a-col :span="12">
                <a-form-item
                  label="角色名称"
                  name="name"
                  :rules="[{required: true, message: '请填写角色名称'}]"
                >
                  <a-input
                    v-model:value="form.name"
                    placeholder="请填写角色名称"
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="排序">
                  <a-input
                    type="number"
                    v-model:value="form.sortId"
                    placeholder="请填写排序"
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="备注">
                  <a-input
                    v-model:value="form.remark"
                    placeholder="请填写备注"
                  ></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </template>

          <template v-if="handleType === 4 || handleType === 5">
            <a-row :gutter="20">
              <a-col :span="12" v-if="handleType === 4">
                <div class="fs-16 fw-bold mb-10 font-center">菜单权限</div>
                <div style="height: 78vh; overflow: auto">
                  <a-tree
                    v-model:checkedKeys="checkInfo.checkedKeys"
                    checkable
                    default-expand-all
                    :tree-data="treeData"
                    :field-names="fieldNames"
                    @check="checkChange"
                  >
                    <template #title="{title, key}">
                      <span>{{ title }}</span>
                    </template>
                  </a-tree>
                </div>
              </a-col>
              <a-col :span="12" v-if="handleType === 4">
                <div class="fs-16 fw-bold mb-10 font-center">字段权限</div>
              </a-col>
              <a-col :span="24" v-if="handleType === 5">
                <a-form-item
                  label="授权范围"
                  name="dataScopeType"
                  :rules="[{required: true, message: '请选择'}]"
                >
                  <a-select v-model:value="form.dataScopeType">
                    <a-select-option
                      :value="Number(item.code)"
                      v-for="(item, index) in getDicValue('data_scope_type')"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </template>
        </a-form>
        <template #footer>
          <div class="flex-row-xy-center">
            <a-button style="margin-right: 20px" @click="showModalCon(1)"
              >取消</a-button
            >
            <a-button type="primary" @click="showModalCon(2)">提交</a-button>
          </div>
        </template>
      </a-drawer>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {
  roleAdd,
  roleDelete,
  roleDetail,
  rolePage,
  roleEdit,
  menuTree,
  roleOwnMenu,
  roleGrantMenu,
  roleGrantData
} from "@/api/configCenter/auth/role";
import {getDicValue} from "@/utils/common";
import useAppStore from "@/store/app";
import {message, Modal} from "ant-design-vue";
import Pagination from "@/components/pagination/Pagination.vue";

//请求参数
const pageSet = ref({
  pageNo: 1,
  pageSize: 20,
  total: 0
});
const tableData = ref([]); //表格数据
const tableLoading = ref(false); //表格加载
const form = ref({}); //表单数据
const formRef = ref(); //表单ref

/**
 * 获取表格数据
 * @param reset 是否重置
 */
const loadPagination = (reset: boolean = false) => {
  tableLoading.value = true;
  if (reset) {
    tableData.value = [];
    pageSet.value.pageNo = 1;
  }
  rolePage(pageSet.value)
    .then((res) => {
      tableData.value = res.data.rows;
      pageSet.value.total = res.data.totalRows;
      tableLoading.value = false;
    })
    .catch((err) => {
      tableLoading.value = false;
    });
};
loadPagination();

const checkInfo = ref({
  checkedKeys: [],
  halfCheckedKeys: []
});
const oldCheckedKeys = ref([]);
const treeData = ref([]);
const fieldNames = ref({
  children: "children",
  title: "title",
  key: "id"
});
const parentKeys = ref([]);

/**
 * 筛选父级id
 * @param arr 菜单数据
 */
const getParentKeys = (arr: any[]) => {
  let parentKeys: any = [];

  function go(arr) {
    arr.forEach((item: any) => {
      if (item.children && item.children.length) {
        parentKeys.push(item.id);
        go(item.children);
      }
    });
  }

  go(arr);
  return parentKeys;
};

/**
 * 获取全部菜单
 */
const loadMenu = () => {
  menuTree().then((res) => {
    treeData.value = res.data;
    parentKeys.value = getParentKeys(res.data);
  });
};
loadMenu();

const checkChange = (checkedKeys, e) => {
  console.log(checkedKeys, e);
  if (e.checked) {
    checkInfo.value.halfCheckedKeys = e.halfCheckedKeys;
  } else {
    checkInfo.value.halfCheckedKeys = [];
  }
};
const showModal = ref(false);
const handleTitle = ref<string>();
const handleType = ref<number>();

// 判断两个数组是否相等
function arraysEqual(a, b) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (a.length !== b.length) return false;

  for (let i = 0; i < a.length; ++i) {
    let found = false;
    for (let j = 0; j < b.length; ++j) {
      if (a[i] === b[j]) {
        found = true;
        break;
      }
    }
    if (!found) return false;
  }

  return true;
}

const goHandle = (type: number, info?: any, index?: number) => {
  handleType.value = type;
  form.value = {};
  if (formRef.value) {
    //重置验证
    formRef.value.clearValidate();
  }
  if (type === 1) {
    handleTitle.value = "新增";
    showModal.value = true;
    return;
  }
  if (type === 2) {
    handleTitle.value = "编辑";
    useAppStore.loading = true;
    roleDetail({id: info.id}).then((res) => {
      form.value = res.data;
      showModal.value = true;
      useAppStore.loading = false;
    });
    return;
  }
  if (type === 3) {
    Modal.confirm({
      title: "提示",
      content: "确定要删除吗",
      onOk() {
        useAppStore.loading = true;
        roleDelete({id: info.id}).then((res) => {
          tableData.value.splice(index, 1);
          pageSet.value.total--;
          useAppStore.loading = false;
        });
      }
    });
    return;
  }

  if (type === 4) {
    handleTitle.value = "菜单授权";
    useAppStore.loading = true;
    form.value = JSON.parse(JSON.stringify(info));
    roleOwnMenu({id: info.id}).then((res) => {
      let arr: any = [];
      res.data.forEach((item: any) => {
        if (!parentKeys.value.includes(item)) {
          arr.push(item);
        }
      });
      checkInfo.value.checkedKeys = arr;
      // 记录原先的菜单授权 用于判断是否修改了菜单权限 如果没有修改 就不能提交
      oldCheckedKeys.value = arr;
      showModal.value = true;
      useAppStore.loading = false;
    });
    return;
  }

  if (type === 5) {
    handleTitle.value = "数据授权";
    useAppStore.loading = true;
    roleDetail({id: info.id}).then((res) => {
      form.value = res.data;
      showModal.value = true;
      useAppStore.loading = false;
    });
    return;
  }
};

const showModalCon = (type) => {
  if (type == 1) {
    formRef.value.clearValidate();
    showModal.value = false;
  } else if (type == 2) {
    if (handleType.value === 1) {
      formRef.value.validate().then((res) => {
        form.value.roleType = 1;
        form.value.code = form.value.name;
        useAppStore.loading = true;
        roleAdd(form.value).then((res) => {
          loadPagination();
          showModal.value = false;
          useAppStore.loading = false;
        });
      });
    }

    if (handleType.value === 2) {
      formRef.value.validate().then((res) => {
        useAppStore.loading = true;
        roleEdit(form.value).then((res) => {
          loadPagination();
          showModal.value = false;
          useAppStore.loading = false;
        });
      });
    }

    if (handleType.value === 4) {
      formRef.value.validate().then((res) => {
        let arr = [
          ...checkInfo.value.halfCheckedKeys,
          ...checkInfo.value.checkedKeys
        ];
        // 过滤的arr的父级元素
        const filterChildNode = arr.filter(
          (item) => !parentKeys.value.includes(item)
        );
        if (arraysEqual(filterChildNode, oldCheckedKeys.value)) {
          message.warning("目前没有改动,无需修改!");
          return;
        }
        let formData = {
          id: form.value.id,
          grantMenuIdList: arr
        };
        useAppStore.loading = true;
        roleGrantMenu(formData).then((res) => {
          loadPagination();
          showModal.value = false;
          useAppStore.loading = false;
        });
      });
    }

    if (handleType.value === 5) {
      formRef.value.validate().then((res) => {
        useAppStore.loading = true;
        let formData = {
          id: form.value.id,
          dataScopeType: form.value.dataScopeType,
          grantOrgIdList: []
        };
        roleGrantData(formData).then((res) => {
          loadPagination();
          showModal.value = false;
          useAppStore.loading = false;
        });
      });
    }
  }
};

const handleResizeColumn = (w, col) => {
  col.width = w;
};

const columns = ref([
  {
    title: "序号",
    dataIndex: "name",
    align: "center",
    customRender: function ({index}) {
      return index + 1;
    },
    width: 80
  },
  {
    title: "角色名称",
    dataIndex: "name",
    align: "center",
    ellipsis: true,
    resizable: true,
    width: 100,
    minWidth: 100,
    maxWidth: 200
  },
  {
    title: "排序",
    dataIndex: "sortId",
    align: "center",
    ellipsis: true,
    resizable: true,
    width: 100,
    minWidth: 100,
    maxWidth: 200
  },
  {
    title: "备注",
    dataIndex: "remark",
    align: "center"
  },
  {
    title: "创建时间",
    dataIndex: "createdTime",
    align: "center"
  },
  {
    title: "创建人",
    dataIndex: "createdUserName",
    align: "center"
  },
  {
    title: "修改人",
    dataIndex: "updatedUserName",
    align: "center"
  },
  {
    title: "修改时间",
    dataIndex: "updatedTime",
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "handle",
    align: "center",
    width: 220,
    fixed: "right"
  }
]);
</script>

<style lang="less" scoped></style>
